#include "sock.h"

#ifdef WIN32
#else
#include <unistd.h>
#endif

#include <stdio.h>

#define IP_STRING_LEN 15

bool Socket::isInit = false;

bool Socket::initialize() {
#ifdef WIN32
	WSADATA wsaData = {0};
	int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (iResult != 0) {
		printf("WSAStartup failed: %d\n", iResult);
		return false;
	}
#endif
	return true;
}

void Socket::deInitialize() {
#ifdef WIN32
	WSACleanup();
#endif
}

Socket::Socket(int addressFamily, int type, int protocol) {
	if (!Socket::isInit) {
		Socket::initialize();
	}
	this->sockData = INVALID_SOCKET;
	this->sockData = socket(addressFamily, type, protocol);
	if (this->sockData == INVALID_SOCKET) {
		perror("socket");
		return;
	}
	this->addressFamily = addressFamily;
	this->type = type;
	this->protocol = protocol;
	this->ip = new char[IP_STRING_LEN];
}

Socket::~Socket() {
	if (Socket::isInit) {
		Socket::deInitialize();
	}
	delete [] this->ip;
	this->closeConnection();
}

void Socket::setSockData(SOCKET sockData) {
	this->sockData = sockData;
}

const char * Socket::getIpAddress() const {
	return this->ip;
}

void Socket::setIpAddress(const char * ip) {
	if (ip != NULL) {
		int len = strlen(ip);
		if (len <= IP_STRING_LEN) {
			memcpy(this->ip, ip, strlen(ip) + 1);
		}
	}
}

int Socket::sendData(const char * data, int sendLen, int flags) {
	int sendedBytes = send(this->sockData, data, sendLen, flags);
	if (sendedBytes == -1) {
		//perror("send");
	}
	return sendedBytes;
}

int Socket::receiveData(char * data, int receiveLen, int flags, bool reallocMemory) {
	memset(data, 0, receiveLen);
	int recvBytes = recv(this->sockData, data, receiveLen, flags);
	if (recvBytes == -1) {
		//perror("recv");
	}
	return recvBytes;
}

void Socket::closeConnection() {
#ifdef WIN32
	closesocket(this->sockData);
#else
	close(this->sockData);
#endif
}
